$(function() {
	FastClick.attach(document.body);
	window.globalMarkets = null;
	
	var cid = $('#cid').val();
	var typeId = $('#typeId').val();
	// 所有菜场关于此菜的价格
	global__loading.start();
	global__market.get(function(markets) {
		window.globalMarkets = markets;

		global__http.get('/commodity/' + cid + '/type/' + typeId + "/in-markets", null, function(resp) {
			global__loading.stop();
			if(resp.success) {
				renderPrices(resp.result);
			}
		});
	});
}());

function renderPrices(items) {
	var html = '';
	items = items.sort(function(a, b) {
		var aprice = a.price.split('元／')[0]*1;
		var bprice = b.price.split('元／')[0]*1;
		return aprice - bprice;
	});

	items.forEach(function(item) {
		var market = getMarket(item.marketId);
		if(market) {
			html += [
				'<li>',
					'<a href="/market/' + item.marketId + '">',
						'<div>' + market.marketName + '</div>',
						'<div>' + (item.price!=='0.0元／500克' ? (item.price.replace(/／500克/g, '')) : '-') + '</div>',
						'<div>' + market.distance + '</div>',
					'</a>',
				'</li>'
			].join('');
		}
	});
	$('#el-price-content').html(html).show();
}

function renderMarkets4Search(v) {
	var html = '';
	globalMarkets.forEach(function(m) {
		if(!v || m.marketName.indexOf(v) !== -1) {
			html += [
				'<li class="market-item">',
					'<a href="/market/' + m.marketId + '">',
						'<div class="name">' + m.marketName + '</div>',
						'<div class="distance">' + m.distance + '</div>',
					'</a>',
				'</li>'
			].join('');
		}
	});
	$('#el-markets').html(html);
}

function getMarket(marketId) {
	var market;
	for(var i=0; i<globalMarkets.length; i++) {
		if(globalMarkets[i].marketId == marketId) {
			market = globalMarkets[i];
			break;
		}
	}
	return market;
}

function renderMarkets() {
	var html = '';
	globalMarkets.forEach(function(m) {
		html += [
				'<li class="market-item">',
					'<a href="/market/' + m.marketId + '">',
						'<div class="name">' + m.marketName + '</div>',
						'<div class="distance">' + m.distance + '</div>',
					'</a>',
				'</li>'
			].join('');
	});
	$('#el-markets').html(html);
}

/******************************************************************/
function onClickNavTab(index) {
	$('.nav-tab-item .arrow').removeClass('active');
	$('.nav-tab-' + index + ' .arrow').addClass('active');
	$('#el-markets').hide();
	$('#el-price-content').hide();

	// 菜场
	$('#el-markets').show();
	if($('#el-markets li').length === 0) {
		renderMarkets();
	}
}

function onSearch() {
	var v = $('#el-header input').val();
	var html = '';

	$('#el-price-content').hide();
	$('#el-markets').show();
	$('.nav-tab-item .arrow').removeClass('active');
	$('.nav-tab-1 .arrow').addClass('active');

	if(globalMarkets) {
		renderMarkets4Search(v);
	} else {
		global__loading.start();
		global__market.get(function(markets) {
			global__loading.stop();
			window.globalMarkets = markets;
			renderMarkets4Search(v);
		});
	}
}